const XLSX = require('xlsx');
const path = require('path');
const fs = require('fs');
// 读取文件
const filePath = path.join(__dirname, '../language_json/SheetXlsx.xlsx');
const workbook = XLSX.readFile(filePath);
// 获取第一个工作表
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
// 将工作表转换为 JSON 对象
const data = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

function initSheet(list) {
    let iSheet = list
    let SheetList = []
    // console.log("iSheet==",iSheet);
    for (let item of iSheet) {
        let StringReal = JSON.stringify(item.English)
        if (StringReal.indexOf('\\n\\n') !== -1) {
            SheetList = reGetNewList('\\n\\n', SheetList, item);
        }
        else if (StringReal.indexOf('\\n') !== -1) {
            SheetList = reGetNewList('\\n', SheetList, item);
        }
        else {
            SheetList.push(item)
        }
    }
    // console.log("Sheet==", JSON.stringify(SheetList));
    return JSON.stringify(SheetList)
}
function reGetNewList(replaceKey, Sheet, item) {
    let newDataList = [];
    let k = 0
    for (let itemKey in item) {
        let newStringReal = JSON.stringify(item[itemKey]);
        if (newStringReal[0] == '"') {
            newStringReal = newStringReal.replace(newStringReal[0], "")
        }
        if (newStringReal[newStringReal.length - 1] == '"') {
            newStringReal = newStringReal.replace(newStringReal[newStringReal.length - 1], "")
        }
        for (let splitIndex = 0; splitIndex < newStringReal.split(replaceKey).length; splitIndex++) {
            if (k == 0) {
                newDataList.push({})
            }
            newDataList[splitIndex][itemKey] = newStringReal.split(replaceKey)[splitIndex]
        }
        k++;
    }
    return [...Sheet, ...newDataList]
}
function transformXlsx() {
    // console.log("data==",data);
    let list = [];
    let index = 0;
    let titleObj = {}
    for (let item of data) {
        if (index == 0) {
            for (let key of item) {
                titleObj[key] = ""
            }
        } else {
            // console.log("titleObj==",titleObj);
            let itemObj = {}
            let itemObjIndex = 0
            for (let value of item) {
                itemObj[data[0][itemObjIndex]] = value
                itemObjIndex++
            }
            list.push(itemObj)
        }
        index++
        // console.log("list==", list);
    }
    const SheetPath = path.join(__dirname, `../language_json/Sheet.json`);
    const initSheetList = initSheet(list)
    fs.writeFile(SheetPath, initSheetList, 'utf-8', (err) => {
        if (err) {
            console.log(`${SheetPath} replacement successful`)
        } else {
            console.log(`${SheetPath} replacement failed` + err)
        }
    });
    return JSON.parse(initSheetList)
}
const ftx = {
    transformXlsx
};
module.exports = ftx;